package com.atguigu.rabbitmq.routing;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @ClassNAME Producer
 * @Description
 * @Author wuyafeng atguigu
 * @Date 2021/12/1 16:58
 * @Version 1.0
 **/
public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //一、初始化连接
        //1.创建连接对象  默认端口 5672
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //2. 设置主机
        connectionFactory.setHost("localhost");
        //3. 设置需要连接的端口
        connectionFactory.setPort(5672);
        //4. 设置虚拟机，   默认 /
        connectionFactory.setVirtualHost("/");
        //5. 设置用户名和密码
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");

        //二、获取连接对象
        Connection connection = connectionFactory.newConnection();
        //三、获取频道
        Channel channel = connection.createChannel();

        //四、声明交换机， 路由， 然后进行绑定
        String queueName1 = "test_direct_queue1";
        String queueName2 = "test_direct_queue2";
        //先声明队列，  在创建交换机，再将队列和交换机进行绑定
        channel.queueDeclare(queueName1,true,false,false,null);
        channel.queueDeclare(queueName2,true,false,false,null);

        //声明交换机
        channel.exchangeDeclare("text_direct", BuiltinExchangeType.DIRECT,true,false,null);

        //绑定
        channel.queueBind(queueName1,"text_direct","info");
        channel.queueBind(queueName1,"text_direct","error");
        channel.queueBind(queueName1,"text_direct","warning");

        channel.queueBind(queueName2,"text_direct","info");

        //五、发送消息  需要指定routingKey
        String message = "你好，小白兔---";
        channel.basicPublish("text_direct", "error", null, message.getBytes());

        //六、关闭资源
        channel.close();
        connection.close();

    }
}
